<?php
class IndexController extends Controller {

    protected function _init(){
        header("Content-Type:text/html; charset=utf-8");
    }
    private function ajaxReturn($data){
        echo json_encode($data);
        exit;
    }
    private function checkLogin($redirect=true){
        if(isset($_REQUEST['auth']) && isset($_REQUEST['user'])){
            $user = C('USERS');
            $name = trim($_REQUEST['user']);
            $auth = trim($_REQUEST['auth']);
            if(isset($user[$name]) && passwordHash($user[$name]) == $auth){
                return true;
            }
        }
        /*if($redirect){
            redirect('/');
        }*/
        return false;
    }
    public function IndexAction(){
        if($this->checkLogin(false)){
            redirect('/admin/index.php?m=Index&a=Home');
        }else{
            $this->display();
        }
    }
    public function LoginAction(){
        $name = trim($_POST['name']);
        $pwd = trim($_POST['password']);
        $user = C('USERS');
        if(isset($user[$name]) && $user[$name] == $pwd && $pwd != ''){
            setcookie('user', $name);
            setcookie('auth', passwordHash($pwd));
            redirect('/admin/index.php?m=Index&a=Home');
        }else{
            redirect('/');
        }
    }
    public function HomeAction(){
        $this->checkLogin();
        $data = $this->getList();
        $this->assign('list', json_encode($data['list']));
        $this->assign('page', $data['page']);
        $this->display();
    }
    public function GetListAction(){
        $this->checkLogin();
        $data = $this->getList();
        $ret = array('status' => true, 'data' => $data);
        $this->ajaxReturn($ret);
    }
    public function DelAction(){
        $this->checkLogin();
        $Model = M();
        $id = (int)$_POST['id'];
        $Model->execute("INSERT `history` SELECT * FROM `timeline` WHERE id = $id");
        $Model->execute("DELETE FROM `timeline` WHERE id = $id");
        $data = $this->getList();
        $ret = array('status' => true, 'data' => $data);
        $this->ajaxReturn($ret);
    }
    public function SaveAction(){
        $this->checkLogin();
        $Model = M();
        $id = (int)$_POST['id'];
        $type = (int)$_POST['type'];
        $startDate = htmlspecialchars($_POST['startDate']);
        $endDate = 'null';
        if(strtotime($_POST['endDate']) > 0){
            $endDate = htmlspecialchars('\''.$_POST['endDate'].'\'');
        }
        $title = htmlspecialchars($_POST['title']);
        $text = htmlspecialchars($_POST['text']);
        $assetUrl = htmlspecialchars($_POST['url']);
        $assetCaption = htmlspecialchars($_POST['caption']);
        $assetCredit = htmlspecialchars($_POST['credit']);
        $status = (int)$_POST['status'];
        $asset = json_encode(array(
            'media' => $assetUrl,
            'caption' => $assetCaption,
            'credit' => $assetCredit,
            ));
        $asset = $Model->escape($asset);
        if($id > 0){
            $ret = $Model->execute("UPDATE `timeline` set `startDate` = '$startDate', `endDate` = $endDate,
             `headline` = '$title', `text` = '$text', `asset` = '$asset', `status` = $status WHERE `id` = $id");
        }else{
            $ret = $Model->execute("INSERT `timeline` (`type`, `startDate`, `endDate`, `headline`, `text`, `asset`, `status`)
                VALUES ($type, '$startDate', $endDate, '$title', '$text', '$asset', $status)");
        }
        if($ret !== false){
            $ajaxData = array(
                'status' => true,
                'data' => $this->getList(),
                );
        }else{
            $ajaxData = array(
                'status' => false,
                );
        }
        $this->ajaxReturn($ajaxData);
    }
    public function SwitchTempAction(){
        $this->checkLogin();
        $status = (int)$_POST['status'];
        $id = (int)$_POST['id'];
        $Model = M();
        $ret = $Model->execute("UPDATE `timeline` set `status` = $status WHERE `id` = $id");
        if($ret){
            $ajaxData = array(
                'status' => true,
                'data' => $this->getList(),
                );
        }else{
            $ajaxData = array(
                'status' => false,
                );
        }
        $this->ajaxReturn($ajaxData);
    }
    public function UploadAction(){
        $this->checkLogin();
        include "../lib/Uploader.class.php";
        include "../bcs/bcs.class.php";
        $config = array(
            "savePath" => sys_get_temp_dir()."/" ,             //存储文件夹
            "maxSize" => 1000 ,                   //允许的文件最大尺寸，单位KB
            "allowFiles" => array( ".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp" )  //允许的文件格式
        );
        $up = new Uploader( "upfile" , $config );
        $baiduBCS = new BaiduBCS ();
        $info = $up->getFileInfo();
        $response = $baiduBCS->create_object ('cyhloveclj', '/'.$info[ "name" ], $info[ "url" ] );
        $url = 'http://bcs.duapp.com/cyhloveclj/'.$info[ "name" ];
        $type = $_REQUEST['type'];
        $editorId = $_GET['editorid'];

        if($type == "ajax"){
            echo $url;
        }else{
            echo "<script>parent.UM.getEditor('". $editorId ."').getWidgetCallback('image')('" . $url . "','" . $info[ "state" ] . "')</script>";
        }
    }
    private function getList(){
        include '../lib/Page.class.php';
        $Model = M();
        $count = $Model->query("SELECT count(1) c FROM `timeline`");
        $p = new Page($count[0]['c'], 10, '', 'p');
        $page = $p->show();
        $list = $Model->query("SELECT * FROM `timeline` ORDER BY `type` DESC , `startDate` DESC limit {$p->firstRow},{$p->listRows}");
        return array(
            'page' => $page,
            'list' => $list
            );
    }
}
